/* Copyright 2009 Requirements Management System 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.mags.remas.view.widgets;

import org.eclipse.jface.viewers.DialogCellEditor;  
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.mags.common.EngineContext;
import org.mags.remas.model.entity.Entity;
import org.mags.remas.model.entity.EntityCategory;
import org.mags.remas.model.entity.EntityRelationship;
import org.mags.remas.view.dialogs.RelationshipTreeDialog;
import org.mags.remas.view.dialogs.SingletonRelationshipTreeDialog;

/**
 * 
 * @author Mario Gaitan
 *
 */
public class ButtonReferenceCellEditor extends DialogCellEditor {
	public ButtonReferenceCellEditor(Composite parent, int style) {
        super(parent, style);
    }	
	protected Object openDialogBox(Control cellEditorWindow) {
		if(super.getValue()==null)
			return null;
		Entity entity = (Entity)super.getValue();
		SingletonRelationshipTreeDialog treeDialog = SingletonRelationshipTreeDialog.getInstance(super.getControl().getShell().getDisplay());
		EntityCategory entityCategory = EngineContext.getDataContext().getEntityProviderFactory().getEntityTypeProvider().getById(entity.getEntityType().getEntityTypeId()).getEntityCategory();
		treeDialog.setSelectedEntityCategory(entityCategory);
		treeDialog.setText("select a reference");
		treeDialog.setEnabledNoLinkButton(false);
		treeDialog.show();
		treeDialog.setEnabledNoLinkButton(true);
		if(treeDialog.getStatus()==RelationshipTreeDialog.STATUS_CANCELED)
			return entity;
		EntityRelationship selected = treeDialog.getSelectedEntityRelationship();
		return selected.getEntity();
	}
    protected void updateContents(Object value) {
        if (super.getDefaultLabel() == null) {
			return;
		}
        String text = "";
        if (value != null) {
        	Entity reference = (Entity)value;
        	text = reference.getCode();
		}
        super.getDefaultLabel().setText(text);
    }	
}
